<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="load"
    title="选择商品"
    width="1200"
    :close-on-click-modal="false"
    @close="handleClose"
    :z-index="2000"
  >
    <div>
      <div
        style="
          display: flex;
          flex-wrap: wrap;
          align-items: flex-start;
          justify-content: space-between;
          margin-bottom: 8px;
          margin-left: 8px;
        "
      >
        <div class="clearfix flex items-start">
          <el-input
            v-model="form.spu_cn_title"
            placeholder="产品名称"
            class="fl"
            clearable
            style="width: 208px"
          />
          <multi-input
            v-model="form.spu"
            placeholder="SPU"
            class="ml-2 w-50"
          ></multi-input>
          <multi-input
            v-model="form.sku"
            placeholder="SKU"
            class="ml-2 w-50"
          ></multi-input>
        </div>
        <el-button type="primary" @click="queryFun"> 查询 </el-button>
      </div>
    </div>
    <vxe-table
      ref="tableRef"
      height="500"
      style="margin-left: 8px"
      @radio-change="radioChangeEvent"
      @checkbox-change="selectChangeEvent"
      @checkbox-all="selectChangeEvent"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="tableData"
      :checkbox-config="checkboxConfig"
    >
      <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
      <vxe-column title="产品图片" width="80">
        <template #default="{ row }">
          <VImage
            :width="60"
            :height="60"
            :src="row.attr_img_watermark || row.attr_img"
          />
        </template>
      </vxe-column>
      <vxe-column title="SPU" width="100">
        <template #default="{ row }">
          <div>
            <span>{{ row.spu }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="SKU" width="200">
        <template #default="{ row }">
          <div>
            <span>系统SKU:{{ row.sku }}</span>
            <span class="block">自定义: {{ row.custom_sku }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="产品名称" width="200">
        <template #default="{ row }">
          <vText :value="row.sku_cn_title" :line="2" />
        </template>
      </vxe-column>
      <vxe-column title="产品分类" width="200">
        <template #default="{ row }">
          <vText :value="row.spu_category_text" :line="2" />
        </template>
      </vxe-column>

      <vxe-column title="商品状态" width="80">
        <template #default="{ row }">
          <div>
            <span>{{ row.spu_status_text }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="规格" width="80">
        <template #default="{ row }">
          <template v-if="row.specification">
            <div v-for="(item, index) in row.specification" :key="index">
              {{ item.name }}
            </div>
          </template>
          <template v-else>--</template>
        </template>
      </vxe-column>
      <vxe-column title="是否已建模" width="90">
        <template #default="{ row }">
          <div>{{ row.is_build_model_text }}</div>
        </template>
      </vxe-column>

      <vxe-column title="采购未税报价(CNY)" width="150">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price"
            :value="row.supplier_quotation"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购未税价" width="90">
        <template #default="{ row }">
          <dataAuthority
            auth="purchase_untaxed_price"
            :value="row.purchase_untaxed_price"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购含税价" width="90">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price_tax"
            :value="row.unit_price_tax"
          ></dataAuthority>
        </template>
      </vxe-column>
    </vxe-table>
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      "
    >
      <div>
        <vxe-pager
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalResult"
          :page-sizes="[10, 20, 100]"
          @page-change="pageChange"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Jump',
            'PageCount',
            'NextPage',
            'NextJump',
            'Sizes',
            'Total',
          ]"
        >
        </vxe-pager>
      </div>
      <div>
        <el-checkbox style="margin-right: 8px" v-model="includeSKU"
          >带出SPU所有变体SKU</el-checkbox
        >
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="serveFun"> 保存 </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { skuIsCreate, querySkuList } from "../api";
import { ref, reactive, onMounted, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import VImage from "@/components/Image/index.vue";

const totalResult = ref(1);
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
let tableData = ref([]);
let propsData = ref([]);

const props = defineProps({
  getTable: {
    type: Function,
    default: () => {},
  },
});

const checkedData = computed(() => {
  return props.getTable();
});

const data = reactive({
  form: {
    spu: "",
    spu_cn_title: "",
    sku: "",
    custom_sku: "",
  },
  handleType: null,
  includeSKU: false,
  load: false,
});

const { form, handleType, includeSKU, load } = toRefs(data);

const initData = (data = {}) => {
  querySkuList(data).then(({ total, data }) => {
    tableData.value = data;
    totalResult.value = total;
  });
};
const queryFun = () => {
  currentPage.value = 1;
  initData({ ...form.value, pageNum: currentPage.value, pageSize: pageSize.value });
  currentPage.value = 1;
  initData({ ...form.value, pageNum: currentPage.value, pageSize: pageSize.value });
};

const checkboxConfig = reactive({
  labelField: "name",
  checkMethod: ({ row }) => {
    return !checkedData.value.includes(row.id);
  },
});

const open = async () => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  dialogVisible.value = true;
  initData();
};
const handleClose = () => {
  form.value = {};
  dialogVisible.value = false;
};
const pageChange = () => {
  initData({ ...form.value, pageNum: currentPage.value, pageSize: pageSize.value });
};

const serveFun = async () => {
  const skuIds = propsData.value.map((i) => i.id);
  try {
    const res = await skuIsCreate({
      skuId: skuIds,
    });
    if (res.data.is_create.length) {
      ElMessageBox.confirm(
        `SKU: ${res.data.is_create}最近10天内有创建图片任务，是否继续创建`,
        "提示",
        {
          confirmButtonText: "继续创建",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        confirmSave();
      });
    } else {
      confirmSave();
    }
  } catch (e) {
    throw Error(e);
  }
};

const confirmSave = async () => {
  if (includeSKU.value) {
    const spu = [];
    propsData.value.forEach((element) => {
      spu.push(element.spu);
    });

    querySkuList({
      spu: [...new Set(spu)],
    }).then((res) => {
      const product_list = res.data;
      emits("addPictureListQuery", product_list);
      handleClose();
    });
  } else {
    emits("addPictureListQuery", reactive(propsData.value));
    handleClose();
  }
};

const tableRef = ref();

const clearSelectEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    $table.clearCheckboxRow();
  }
};

const radioChangeEvent = ({ $table }) => {
  const records = $table.getRadioRecord();
  propsData.value = JSON.parse(JSON.stringify(records));
};

const selectChangeEvent = ({ $table }) => {
  const records = $table.getCheckboxRecords();
  propsData.value = JSON.parse(JSON.stringify(records));
};

const emits = defineEmits("addPictureListQuery");
defineExpose({ open, clearSelectEvent });
</script>
<style scoped>
:deep(.vxe-pager.is--perfect) {
  border: 0;
}
</style>
